﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;

using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;

namespace Baosight.ZNH.ZMCE.UI
{
    public partial class ZMCEA1 : EFViewCmes
    {
        private DispatcherTimer timer = new DispatcherTimer();
        private string chartType = "";

        public ZMCEA1()
        {
            InitializeComponent();

            this.fdBeginTime.Value = DateTime.Now.AddDays(-90).ToString(Common.DATETIME_FORMAT);
            this.fdEndTime.Value = DateTime.Now.ToString(Common.DATETIME_FORMAT);

            InitChart(this.MTTRChart, "平均恢复时间(MTTR)统计图");
            InitChart(this.MTBFChart, "平均无故障时间(MTBF)统计图");

            this.Loaded += new RoutedEventHandler(ZMCEA1_Loaded);
        }

        #region 初始化，加载树目录

        /// <summary>
        /// 初始化，页面加载时，查询树目录节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ZMCEA1_Loaded(object sender, RoutedEventArgs e)
        {
            EIInfo inInfo = new EIInfo();

            inInfo.Attributes[EIConstants.ServiceNameKey] = "ZMCEA0";
            inInfo.Attributes[EIConstants.MethodNameKey] = "initLoad";

            this.Submit(inInfo, loadSubmitCompleted);
        }

        /// <summary>
        /// 返回树目录节点数据，加载树目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void loadSubmitCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                EFWindow.Alert("数据库查询数据错误，请检查服务器/数据库连接！");
                return;
            }
            else
            {
                EIInfo outInfo = e.EIInfo;

                EIBlock mineBlock = outInfo.GetBlock("mine");
                EIBlock systemBlock = outInfo.GetBlock("system");
                EIBlock unitBlock = outInfo.GetBlock("unit");

                if ((mineBlock != null) && (systemBlock != null) && (unitBlock != null))
                {
                    AddItemsToTree(mineBlock, systemBlock, unitBlock);
                    this.tree.ExpandAll();
                }
                else
                {
                    return;
                }
            }
        }

        /// <summary>
        /// 添加矿井、生产系统、生产单元3级树目录结构
        /// </summary>
        /// <param name="mine"></param>
        /// <param name="system"></param>
        /// <param name="device"></param>
        private void AddItemsToTree(EIBlock mine, EIBlock system, EIBlock unit)
        {
            IList<EIRow> mineRows = mine.GetRows();

            if (mineRows.Count > 0)
            {
                IDictionary<string, EFTreeItem> mineDic = new Dictionary<string, EFTreeItem>();
                IDictionary<string, EFTreeItem> systemDic = new Dictionary<string, EFTreeItem>();

                for (int i = 0; i < mineRows.Count; i++)
                {
                    EIRow row = mineRows[i];
                    EFTreeItem item = new EFTreeItem();
                    item.eHeader = row["fdName"];
                    item.ItemObject = row;
                    item.ExpandAll();
                    this.tree.AddTreeItem(item);

                    string fdId = row["fdKeyId"].ToString().Trim();    //矿井ID
                    mineDic.Add(fdId, item);
                }

                AddChildItems(system, "fdMineId", "fdName", mineDic, systemDic);
                AddChildItems(unit, "fdProductionSystemId", "fdName", systemDic, null);
            }
        }

        /// <summary>
        /// 将Blcok中的节点添加到父节点下
        /// </summary>
        /// <param name="block"></param>
        /// <param name="parentIndex"></param>
        /// <param name="nameIndex"></param>
        /// <param name="parentDic"></param>
        /// <param name="childDic"></param>
        private void AddChildItems(EIBlock block, string parentIndex, string nameIndex,
            IDictionary<string, EFTreeItem> parentDic, IDictionary<string, EFTreeItem> childDic)
        {
            IList<EIRow> rows = block.GetRows();

            if (rows.Count > 0)
            {
                for (int i = 0; i < rows.Count; i++)
                {
                    string parentId = rows[i][parentIndex].ToString().Trim();

                    if (parentDic.ContainsKey(parentId))
                    {
                        EFTreeItem parentItem = parentDic[parentId];

                        EFTreeItem item = new EFTreeItem();
                        item.eHeader = rows[i][nameIndex];
                        item.ItemObject = rows[i];
                        item.ExpandAll();

                        parentItem.AddTreeItem(item);

                        if (childDic != null)
                        {
                            string fdId = rows[i]["fdKeyId"].ToString().Trim();    //
                            childDic.Add(fdId, item);
                        }
                    }
                }
            }
        }

        #endregion

        #region 查询设备效率相关信息

        /// <summary>
        /// "查询"按钮响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnQueryButtonClick(object sender, RoutedEventArgs e)
        {
            string deviceNo = "";
            string deviceName = "";
            string startTime = "";
            string stopTime = "";

            if ((this.fdCode.Value != null) && (!this.fdCode.Value.ToString().Trim().Equals("")))
            {
                deviceNo = this.fdCode.Value.ToString().Trim();
            }

            if ((this.fdName.Value != null) && (!this.fdName.Value.ToString().Trim().Equals("")))
            {
                deviceName = this.fdName.Value.ToString().Trim();
            }

            if ((this.fdBeginTime != null))   //过滤开始日期可能输入的非法字符
            {
                string tmpStart = this.fdBeginTime.GetDataValue().ToString().Trim();
                this.fdBeginTime.Value = "";        //必须先置成""后，再赋值，才会在页面中生效
                this.fdBeginTime.Value = tmpStart;
            }

            if (this.fdEndTime != null)         //过滤结束日期可能输入的非法字符
            {
                string tmpEnd = this.fdEndTime.GetDataValue().ToString().Trim();
                this.fdEndTime.Value = "";      //必须先置成""后，再赋值，才会在页面中生效
                this.fdEndTime.Value = tmpEnd;
            }

            if (!GetDateTimePara(this.fdBeginTime, this.fdEndTime, ref startTime, ref stopTime))
            {
                return;
            }

            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdNo");
            Common.AddColumnToBlock(block, "fdName");
            Common.AddColumnToBlock(block, "fdStartTime");
            Common.AddColumnToBlock(block, "fdEndTime");

            EIRow row = new EIRow();
            row.Add("fdNo", deviceNo);
            row.Add("fdName", deviceName);
            row.Add("fdStartTime", startTime);
            row.Add("fdEndTime", stopTime);

            block.AddRow(row);

            QueryEffeciencyInfo(block);
        }

        /// <summary>
        /// 校验、获取起始、结束日期的查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private bool GetDateTimePara(EFDataField fdStart, EFDataField fdEnd, ref string startTime, ref string stopTime)
        {
            startTime = "";
            stopTime = "";

            if ((fdStart != null) && (!fdStart.GetDataValue().ToString().Trim().Equals("")))
            {
                startTime = fdStart.Value.ToString().Trim() + " " + "00:00:00";
            }

            if ((fdEnd != null) && (!fdEnd.Value.ToString().Trim().Equals("")))
            {
                stopTime = fdEnd.Value.ToString().Trim() + " " + "23:59:59";
            }

            DateTime currentDate = DateTime.Parse(DateTime.Now.ToString(Common.DATETIME_FORMAT) + " " + "23:59:59");

            if ((!startTime.Equals("")) || (!stopTime.Equals("")))
            {
                if ((!startTime.Equals("")) && (!stopTime.Equals("")))
                {
                    DateTime beginTime = Convert.ToDateTime(startTime);
                    DateTime endTime = Convert.ToDateTime(stopTime);

                    if (beginTime.CompareTo(currentDate) > 0 || endTime.CompareTo(currentDate) > 0)
                    {
                        EFWindow.Alert("选择日期不能大于当前日期，请重新选择！");
                        return false;
                    }

                    if (beginTime.CompareTo(endTime) > 0)
                    {
                        EFWindow.Alert("开始日期不能大于结束日期，请重新选择！");
                        return false;
                    }
                }
                else if ((!startTime.Equals("")) && (stopTime.Equals("")))
                {
                    DateTime beginTime = Convert.ToDateTime(startTime);

                    if (beginTime.CompareTo(currentDate) > 0)
                    {
                        EFWindow.Alert("开始日期不能大于当前日期，请重新选择！");
                        return false;
                    }

                    fdEnd.Value = DateTime.Now.ToString(Common.DATETIME_FORMAT);
                    stopTime = DateTime.Now.ToString();
                }
                else if ((startTime.Equals("")) && (!stopTime.Equals("")))
                {
                    DateTime endTime = Convert.ToDateTime(stopTime);

                    if (endTime.CompareTo(currentDate) > 0)
                    {
                        EFWindow.Alert("结束日期不能大于当前日期，请重新选择！");
                        return false;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// 查询设备效率信息
        /// </summary>
        /// <param name="block"></param>
        public void QueryEffeciencyInfo(EIBlock block)
        {
            EIInfo inInfo = new EIInfo();

            inInfo.AddBlock(block);
            inInfo.Attributes[EIConstants.ServiceNameKey] = "ZMCEA0";
            inInfo.Attributes[EIConstants.MethodNameKey] = "queryEffectInfo";

            this.Submit(inInfo, QueryEffeciencyInfoSubmitCompleted);
        }

        /// <summary>
        /// 返回设备效率相关数据信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryEffeciencyInfoSubmitCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                EFWindow.Alert("数据库查询错误，请检查服务器/数据库连接！");
                return;
            }
            else
            {
                EIInfo outInfo = e.EIInfo;

                EIBlock equipmentBlock = outInfo.GetBlock("equipment");
                EIBlock runBlock = outInfo.GetBlock("run");
                EIBlock faultBlock = outInfo.GetBlock("fault");

                if ((equipmentBlock != null) && (equipmentBlock.GetRowCount() > 0))
                {
                    IList<EIRow> equipmentList = equipmentBlock.GetRows();
                    IDictionary<string, EIRow> equipmentDic = new Dictionary<string, EIRow>();

                    for (int i = 0; i < equipmentList.Count; i++)
                    {
                        equipmentDic.Add(equipmentList[i]["fdKeyId"].ToString().Trim(), equipmentList[i]);
                    }

                    EIInfo effectInfo = GenerateEffectInfo(equipmentDic, runBlock, faultBlock);

                    this.equipmentEffectGrid.ItemsSource = null;
                    this.equipmentEffectGrid.UpdateData(effectInfo);

                    Common.ClearChart(this.MTTRChart);
                    Common.ClearChart(this.MTBFChart);
                }
                else
                {
                    this.equipmentEffectGrid.ItemsSource = null;
                    Common.ClearChart(this.MTTRChart);
                    Common.ClearChart(this.MTBFChart);
                }
            }
        }

        /// <summary>
        /// 生成效率分析数据EIInfo
        /// </summary>
        /// <param name="equipment"></param>
        /// <param name="operation"></param>
        /// <param name="fault"></param>
        private EIInfo GenerateEffectInfo(IDictionary<string, EIRow> equipment, EIBlock operation, EIBlock fault)
        {
            EIInfo info = new EIInfo();
            EIBlock block = new EIBlock("effectResult");
            Common.AddColumnToBlock(block, "fdNo");
            Common.AddColumnToBlock(block, "fdName");
            Common.AddColumnToBlock(block, "fdSystemName");
            Common.AddColumnToBlock(block, "fdMineName");
            Common.AddColumnToBlock(block, "fdAvrRecoverytim");
            Common.AddColumnToBlock(block, "fdAvrNormaltime");
            Common.AddColumnToBlock(block, "fdAvgRecov");
            Common.AddColumnToBlock(block, "fdAvgNoFault");

            foreach (KeyValuePair<string, EIRow> item in equipment)
            {
                int faultCount = 0;
                string equipmentId = item.Key;
                EIRow row = item.Value;

                CalAvgRecovTime(equipmentId, row, fault, ref faultCount);
                CalAvgNoFaultTime(equipmentId, row, operation, faultCount);

                block.AddRow(row);
            }

            block.Set(EIConstants.LimitKey, "10");      //设置EIblock的分页属性
            block.Set(EIConstants.OffsetKey, "0");
            block.Set(EIConstants.TotalRecordsKey, block.GetRowCount().ToString());
            block.Set(EIConstants.ShowCount, "true");

            info.AddBlock(block);

            return info;
        }

        /// <summary>
        /// 计算平均恢复时间
        /// </summary>
        /// <param name="fdId"></param>
        /// <param name="row"></param>
        /// <param name="fault"></param>
        private void CalAvgRecovTime(string fdId, EIRow row, EIBlock fault, ref int faultCount)
        {
            double sumTime = 0.0;
            faultCount = 0;

            IList<EIRow> faultList = fault.GetRows();

            if (faultList.Count > 0)
            {
                var query = faultList.Where(p => p["fdKeyId"].ToString().Trim().Equals(fdId)).ToList();

                if (query.Count > 0)
                {
                    foreach (var item in query)
                    {
                        faultCount = Convert.ToInt32(item["fdFaultCount"].ToString().Trim());
                        DateTime beginClock = DateTime.Now;
                        DateTime endClock = DateTime.Now;

                        if ((item["fdBeginClock"] != null) && (!item["fdBeginClock"].ToString().Trim().Equals("")))
                        {
                            beginClock = DateTime.Parse(item["fdBeginClock"].ToString().Trim());
                        }

                        if ((item["fdEndClock"] != null) && (!item["fdEndClock"].ToString().Trim().Equals("")))
                        {
                            endClock = DateTime.Parse(item["fdEndClock"].ToString().Trim());
                        }

                        TimeSpan time = endClock.Subtract(beginClock);      //计算恢复时间
                        sumTime += time.Days * 24 * 60 + time.Hours * 60 + time.Minutes + ((double)time.Seconds / 60);  //最小单位为分钟
                    }
                }
            }

            if (Common.IsZero(sumTime))    //计算平均恢复时间
            {
                row.Add("fdAvgRecov", Common.ZERO);
            }
            else
            {
                if (faultCount <= 0)
                {
                    row.Add("fdAvgRecov", sumTime.ToString());
                    Common.DecimalFilter(row, "fdAvgRecov", 2);      //保留两位小数
                }
                else
                {
                    row.Add("fdAvgRecov", (sumTime / faultCount).ToString());
                    Common.DecimalFilter(row, "fdAvgRecov", 2);      //保留两位小数
                }
            }
        }

        /// <summary>
        /// 计算平均无故障时间
        /// </summary>
        /// <param name="fdId"></param>
        /// <param name="row"></param>
        /// <param name="operation"></param>
        /// <param name="fault"></param>
        private void CalAvgNoFaultTime(string fdId, EIRow row, EIBlock operation, int faultCount)
        {
            double runTime = 0.0;

            IList<EIRow> operationList = operation.GetRows();

            if (operationList.Count > 0)    //查询运行时间
            {
                var query = operationList.Where(p => p["fdKeyId"].ToString().Trim().Equals(fdId)).ToList();

                if (query.Count > 0)
                {
                    foreach (var item in query)
                    {
                        if ((item["fdSumRunTime"] != null) && (!item["fdSumRunTime"].ToString().Trim().Equals("")))
                        {
                            runTime = Double.Parse(item["fdSumRunTime"].ToString().Trim());
                        }
                        break;
                    }
                }
            }

            if (Common.IsZero(runTime))    //计算平均无故障时间
            {
                row.Add("fdAvgNoFault", Common.ZERO);
            }
            else
            {
                if (faultCount <= 0)
                {
                    row.Add("fdAvgNoFault", runTime.ToString());
                    Common.DecimalFilter(row, "fdAvgNoFault", 2);   //保留2位小数
                }
                else
                {
                    row.Add("fdAvgNoFault", (runTime / (faultCount + 1)).ToString());   //计算平均无故障时间
                    Common.DecimalFilter(row, "fdAvgNoFault", 2);
                }
            }
        }

        #endregion

        #region 刷新RadChart统计图

        /// <summary>
        /// 勾选设备效率记录响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void equipmentEffectGrid_CheckChaged(object sender, CheckChangedEventArgs e)
        {
            timer.Interval = new TimeSpan(0, 0, 0, 0, 100);     //定时器时长：100ms
            timer.Tick += new EventHandler(GetCheckedRows);

            if (!timer.IsEnabled)
                timer.Start();
        }

        /// <summary>
        /// 获取勾选的设备效率记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetCheckedRows(object sender, EventArgs e)
        {
            if (timer != null)
            {
                timer.Stop();
            }


            IList<EIRow> checkedRows = this.equipmentEffectGrid.GetCheckedEIRows();

            if (checkedRows.Count > 0)
            {
                UpdateChartData(this.MTTRChart, checkedRows, "fdAvgRecov", chartType);
                UpdateChartData(this.MTBFChart, checkedRows, "fdAvgNoFault", chartType);
            }
            else
            {
                Common.ClearChart(this.MTTRChart);
                Common.ClearChart(this.MTBFChart);
                return;
            }
        }

        /// <summary>
        /// 初始化RadChart图
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        private void InitChart(RadChart chartName, string title)
        {
            chartName.DefaultView.ChartTitle.Content = title;
            chartName.DefaultView.ChartTitle.FontSize = 12;

            chartName.DefaultView.ChartLegend.Header = "";
            chartName.DefaultView.ChartLegend.FontSize = 8;
            chartName.DefaultView.ChartLegend.MaxWidth = 100;

            chartName.DefaultView.ChartArea.FontSize = 8;

            chartName.DefaultView.ChartArea.AxisX.LayoutMode = AxisLayoutMode.Inside;
            chartName.DefaultView.ChartArea.AxisX.AutoRange = true;
            chartName.DefaultView.ChartArea.AxisX.LabelRotationAngle = 45;
            chartName.DefaultView.ChartArea.AxisX.DefaultLabelFormat = "MMM-yy";

            chartName.DefaultView.ChartArea.AxisY.AutoRange = true;
            chartName.DefaultView.ChartArea.AxisY.DefaultLabelFormat = "#VAL ";
            chartName.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            chartName.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            chartName.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

            chartName.Visibility = Visibility.Visible;

        }

        /// <summary>
        /// 刷新RadChart图数据
        /// </summary>
        /// <param name="chartName"></param>
        /// <param name="data"></param>
        private void UpdateChartData(RadChart chartName, IList<EIRow> data, string colIndex, string chartType)
        {
            if (chartName.DefaultView.ChartArea.DataSeries != null)
            {
                chartName.DefaultView.ChartArea.AdditionalYAxes.Clear();
                chartName.DefaultView.ChartArea.DataSeries.Clear();
            }

            if (data.Count > 0)
            {
                chartName.DefaultView.ChartArea.DataSeries.Add(GenerateSeries(data, colIndex, chartType));
            }
        }

        /// <summary>
        /// 生成统计分析图表的柱状图
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        private DataSeries GenerateSeries(IList<EIRow> data, string colIndex, string type)
        {
            DataSeries series = new DataSeries();

            switch (type)
            {
                case "Bar":
                    series.Definition = new BarSeriesDefinition();
                    series.Definition.LegendItemLabelFormat = "#XCAT";
                    series.Definition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;

                    AddDataToSeries(series, data, colIndex);
                    break;
                case "Horizontal Bar":
                    series.Definition = new HorizontalBarSeriesDefinition();
                    series.Definition.LegendItemLabelFormat = "#XCAT";
                    series.Definition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;

                    AddDataToSeries(series, data, colIndex);
                    break;
                case "Pie":
                    series.Definition = new PieSeriesDefinition();
                    series.Definition.AxisName = string.Empty;

                    series.Definition.ShowItemLabels = true;
                    series.Definition.ItemLabelFormat = "#VAL ";

                    for (int i = 0; i < data.Count; i++)
                    {
                        double value = Double.Parse(data[i][colIndex].ToString().Trim());

                        series.Add(new DataPoint(value) { LegendLabel = data[i]["fdName"].ToString().Trim() });
                    }
                    break;
                default:
                    series.Definition = new BarSeriesDefinition();
                    series.Definition.LegendItemLabelFormat = "#XCAT";
                    series.Definition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;
                    AddDataToSeries(series, data, colIndex);
                    break;
            }
            //series.Definition.AxisName = string.Empty;

            return series;
        }

        /// <summary>
        /// 添加统计分析图表的数据
        /// </summary>
        /// <param name="series"></param>
        /// <param name="row"></param>
        private void AddDataToSeries(DataSeries series, IList<EIRow> data, string colIndex)
        {
            for (int i = 0; i < data.Count; i++)
            {
                EIRow row = data[i];

                series.Definition.AxisName = string.Empty;
                string label = row["fdName"].ToString().Trim();
                double avgRecov = Double.Parse(row[colIndex].ToString().Trim());

                series.Add(new DataPoint(avgRecov) { LegendLabel = label, XCategory = label });
            }
        }

        /// <summary>
        /// 点击图表类型按钮时的事件响应
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            if (btn != null)
            {
                btn.Focus();

                if (chartType.Equals(btn.Tag.ToString().Trim()))
                {
                    return;
                }
                else
                {
                    chartType = btn.Tag.ToString().Trim();
                }
            }
            else
            {
                return;
            }

            IList<EIRow> list = this.equipmentEffectGrid.GetCheckedEIRows();

            if (list.Count > 0)
            {
                switch (chartType)
                {
                    case "Bar":
                        UpdateChartData(this.MTTRChart, list, "fdAvgRecov", Common.CHART_BAR);
                        UpdateChartData(this.MTBFChart, list, "fdAvgNoFault", Common.CHART_BAR);
                        break;
                    case "Horizontal Bar":
                        UpdateChartData(this.MTTRChart, list, "fdAvgRecov", Common.CHART_HORIZONTALBAR);
                        UpdateChartData(this.MTBFChart, list, "fdAvgNoFault", Common.CHART_HORIZONTALBAR);
                        break;
                    case "Pie":
                        UpdateChartData(this.MTTRChart, list, "fdAvgRecov", Common.CHART_PIE);
                        UpdateChartData(this.MTBFChart, list, "fdAvgNoFault", Common.CHART_PIE);
                        break;
                    default:
                        UpdateChartData(this.MTTRChart, list, "fdAvgRecov", Common.CHART_BAR);
                        UpdateChartData(this.MTBFChart, list, "fdAvgNoFault", Common.CHART_BAR);
                        break;
                }
            }
        }

        #endregion

        #region 点击树目录响应处理

        /// <summary>
        /// 点击树目录节点事件响应
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tree_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if ((sender as EFTree).SelectedItem == null)
                return;

            Common.ClearChart(this.MTTRChart);
            Common.ClearChart(this.MTBFChart);

            this.equipmentEffectGrid.ItemsSource = null;

            EFTreeItem selectItem = (sender as EFTree).SelectedItems[0] as EFTreeItem;
            IList<EIRow> queryList = new List<EIRow>();

            if (selectItem.ParentItem != null)
            {
                if (selectItem.ParentItem.ParentItem != null)
                {
                    //EFWindow.Alert("生产单元节点！");
                    EIRow row = selectItem.ItemObject as EIRow;
                    queryList.Add(row);
                }
                else
                {
                    //EFWindow.Alert("生产系统节点！");
                    AddTreeItems(queryList, selectItem);
                }
            }
            else
            {
                //if (selectItem.IsRootItem)
                //    EFWindow.Alert("矿井节点！");
                AddTreeItems(queryList, selectItem);
            }

            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdKeyId");

            if (queryList.Count > 0)
            {
                AddQueryBlock(block, queryList);
                QueryEffeciencyInfo(block);
            }
        }

        /// <summary>
        /// 遍历EFTreeItem下的所有叶子节点
        /// </summary>
        /// <param name="list"></param>
        /// <param name="treeItem"></param>
        private void AddTreeItems(IList<EIRow> list, EFTreeItem treeItem)
        {
            if (treeItem.HasItems)
            {
                ItemCollection childItems = treeItem.Items;

                for (int i = 0; i < childItems.Count; i++)
                {
                    EFTreeItem item = (EFTreeItem)childItems[i];

                    if (item.HasItems)
                    {
                        ItemCollection nextChildItems = item.Items;

                        for (int j = 0; j < nextChildItems.Count; j++)
                        {
                            EFTreeItem nextItem = (EFTreeItem)nextChildItems[j];

                            EIRow nextRow = nextItem.ItemObject as EIRow;
                            list.Add(nextRow);
                        }
                    }
                    else
                    {
                        if ((item.ParentItem != null) && (!item.ParentItem.IsRootItem))
                        {
                            EIRow row = item.ItemObject as EIRow;
                            list.Add(row);
                        }
                    }
                }
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 拼接查询字段
        /// </summary>
        /// <param name="list"></param>
        /// <param name="treeItem"></param>
        private void AddQueryBlock(EIBlock block, IList<EIRow> list)
        {
            string euqipmentId = "'" + list[0]["fdKeyId"].ToString().Trim() + "'";

            for (int i = 1; i < list.Count; i++)
            {
                euqipmentId = euqipmentId + ", '" + list[i]["fdKeyId"].ToString().Trim() + "'";
            }

            EIRow row = new EIRow();
            row.Add("fdKeyId", euqipmentId);

            block.AddRow(row);
        }

        #endregion

    }
}
